/**
 * All rights Reserved, Designed By 姑苏区政府大数据中心
 *
 * @Copyright: 2019 姑苏区政府大数据中心. All rights reserved.
 * 注意：本内容仅限于姑苏区政府大数据中心内部传阅，禁止外泄以及用于其他的商业目
 */
package com.dci.service.impl.project;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dci.dao.pms.project.ProjectManagerMapper;
import com.dci.dao.pms.project.ProjectScheduleMapper;
import com.dci.model.project.ProjectManager;
import com.dci.model.project.ProjectSchedule;
import com.dci.param.SearchMap;
import com.dci.result.JsonData;
import com.dci.result.PageResult;
import com.dci.service.project.ProjectExamineService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @version V1.0
 * @Package com.dci.service.impl.project
 * @Description: 项目管理实现类
 * @author: 张星亮
 * @date: 2019/2/25
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class ProjectExamineServiceImpl implements ProjectExamineService {

    @Resource
    private ProjectManagerMapper projectManagerMapper;

    @Resource
    private ProjectScheduleMapper projectScheduleMapper;

    /**
     * 项目管理 季度审核
     *
     * @param projectSchedule
     * @return JsonData JsonData类型
     */
    @Override
    public JsonData updateProjectExamine(ProjectSchedule projectSchedule) {
        if ("1".equals(projectSchedule.getStatus())) {
            ProjectManager projectManager = ProjectManager.builder()
                    .auditStatus(projectSchedule.getStatus())
                    .operate("0")
                    .id(projectSchedule.getProjectId())
                    .build();
            ProjectSchedule p = projectScheduleMapper.queryScheduleInfo(projectSchedule.getId());
            ProjectManager projectManager1 = projectManagerMapper.selectByPrimaryKey(projectManager);
            String yearDisFunds = projectManager1.getYearDisFunds();
            String yearInvestmentAdjustments = projectManager1.getYearInvestmentAdjustments();
            JSONObject jsonObject = JSON.parseObject(yearDisFunds);
            JSONObject jsonObject1 = JSON.parseObject(yearInvestmentAdjustments);
            String projectYear = p.getProjectYear();
            try {
                int yearPay = 0;
                if (jsonObject.get(projectYear) != null) {
                    yearPay = Integer.parseInt(jsonObject.get(projectYear).toString());
                }
                int quarterAmountPay = Integer.parseInt(p.getQuarterAmountPay());
                int yearInvestmentAdjustments1 = 0;
                if (jsonObject1.get(projectYear) != null) {
                    yearInvestmentAdjustments1 = Integer.parseInt(jsonObject1.get(projectYear).toString());
                }
                int investAdjust = Integer.parseInt(p.getInvestAdjust());
                String totalInvestment = String.valueOf(yearInvestmentAdjustments1 + investAdjust);
                String totalYearPay = String.valueOf(yearPay + quarterAmountPay);
                String quater = projectManager1.getQuarterlyProgress();
                String desc = "";
                String queryChar = quater.substring(quater.indexOf("**") + 2, quater.lastIndexOf("**"));
                String year = queryChar.substring(0, queryChar.indexOf("年"));
                String quat = "";
                if (quater.indexOf("季度**") > -1) {
                    quat = queryChar.substring(queryChar.indexOf("第") + 1, queryChar.indexOf("季度"));
                }
                if (quater.indexOf("月**") > -1) {
                    quat = queryChar.substring(queryChar.indexOf("年") + 1, queryChar.indexOf("月"));
                }

                if (Integer.parseInt(p.getProjectYear()) >= Integer.parseInt(year)) {
                    int oldMonth = 0;
                    int newMonth = 0;

                    if (quat != null) {
                        if (quat.equals("一")) {
                            oldMonth = 3;
                        } else if (quat.equals("二")) {
                            oldMonth = 6;
                        } else if (quat.equals("三")) {
                            oldMonth = 9;
                        } else if (quat.equals("四")) {
                            oldMonth = 12;
                        } else {
                            oldMonth = Integer.parseInt(quat);
                        }
                    }

                    String qu = p.getProjectQuarter();
                    if (qu != null) {
                        if (qu.equals("一")) {
                            newMonth = 3;
                            desc = "**" + p.getProjectYear() + "年第" + p.getProjectQuarter() + "季度**";
                        } else if (qu.equals("二")) {
                            desc = "**" + p.getProjectYear() + "年第" + p.getProjectQuarter() + "季度**";
                            newMonth = 6;
                        } else if (qu.equals("三")) {
                            desc = "**" + p.getProjectYear() + "年第" + p.getProjectQuarter() + "季度**";
                            newMonth = 9;
                        } else if (qu.equals("四")) {
                            desc = "**" + p.getProjectYear() + "年第" + p.getProjectQuarter() + "季度**";
                            newMonth = 12;
                        } else {
                            desc = "**" + p.getProjectYear() + "年" + p.getProjectQuarter() + "月**";
                            newMonth = Integer.parseInt(qu);
                        }
                    }
                    if (oldMonth <= newMonth) {
                        projectManager1.setQuarterlyProgress(p.getProjectSchedule() + desc);
                        projectManager1.setQuarterPlan(p.getProjectPlan() + desc);

                    }
                }
                jsonObject.put(projectYear, totalYearPay);
                jsonObject1.put(projectYear, totalInvestment);
                int disbursedFundsCount = 0;
                int investmentAdjustmentCount = 0;
                Iterator< String > obj_Iterator = jsonObject.keySet().iterator();
                while (obj_Iterator.hasNext()) {
                    String key = obj_Iterator.next();
                    int value = Integer.parseInt(String.valueOf(jsonObject.get(key)));
                    disbursedFundsCount += value;
                }

                Iterator< String > obj1_Iterator = jsonObject1.keySet().iterator();
                while (obj1_Iterator.hasNext()) {
                    String key = obj1_Iterator.next();
                    int value = Integer.parseInt(String.valueOf(jsonObject1.get(key)));
                    investmentAdjustmentCount += value;
                }

                projectManager1.setDisbursedFunds(String.valueOf(disbursedFundsCount));
                projectManager1.setInvestmentAdjustment(String.valueOf(investmentAdjustmentCount));
                projectManager1.setYearDisFunds(jsonObject.toJSONString());
                projectManager1.setYearInvestmentAdjustments(jsonObject1.toJSONString());
                projectManager1.setAuditStatus(projectSchedule.getStatus());
                int num = projectManagerMapper.updateByPrimaryKeySelective(projectManager1);
                if (num > 0) {
                    int num1 = projectScheduleMapper.updateProjectSchedule(projectSchedule);
                    if (num1 > 0) {
                        return JsonData.success("", 906);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            ProjectManager projectManager = ProjectManager.builder()
                    .auditStatus("3")
                    .operate("0")
                    .id(projectSchedule.getProjectId())
                    .build();
            int num = projectManagerMapper.updateByPrimaryKeySelective(projectManager);
            if (num > 0) {
                int num1 = projectScheduleMapper.updateProjectSchedule(projectSchedule);
                if (num1 > 0) {
                    return JsonData.success("", 906);
                }
            }
        }
        return JsonData.success("", 911);
    }

    /**
     * 根据条件分页查询项目 加 季度
     *
     * @param searchMap 查询条件
     * @param pageNum   页数
     * @param pageSize  每页总数
     * @return PageResult PageResult对象
     */
    @Override
    public PageResult findList(SearchMap searchMap, Integer pageNum, Integer pageSize) {
        // 分页插件
        PageHelper.startPage(pageNum, pageSize);
        // 项目信息
        List< ProjectManager > projectManagers = projectManagerMapper.queryByAny(searchMap);

        // 季度信息
        List< ProjectSchedule > projectSchedules = projectScheduleMapper.queryProjectScheduleList();
        if (projectManagers.size() > 0) {
            // 遍历项目信息
            for (ProjectManager projectManager : projectManagers) {
                String columns = projectManager.getFieldName();
                if (columns != null && !"".equals(columns)) {
                    Map map = (Map) JSONObject.parse(columns);
                    String queryColumns = "";
                    for (int i = 0; i < map.size(); i++) {
                        if (queryColumns == "") {
                            queryColumns += "column_" + i;
                        } else {
                            queryColumns += "," + "column_" + i;
                        }
                    }
                    if (queryColumns != "") {
                        String sql = "select " + queryColumns + " from pms_project_manager where id = '" + projectManager.getId() + "'";
                        JSONObject jsonObject = projectScheduleMapper.queryColumns(sql);
                        if (jsonObject != null) {
                            projectManager.setColumnValues(jsonObject.toString());
                        }
                    }
                }

                if (projectSchedules.size() > 0) {
                    List< ProjectSchedule > projectScheduleList = new ArrayList<>();
                    // 遍历季度信息
                    for (ProjectSchedule projectSchedule1 : projectSchedules) {
                        if (!StringUtils.isEmpty(projectManager.getId()) && !StringUtils.isEmpty(projectSchedule1.getProjectId())) {
                            if (projectManager.getId().equals(projectSchedule1.getProjectId())) {
                                projectScheduleList.add(projectSchedule1);
                            }
                        }
                    }
                    projectManager.setProjectScheduleList(projectScheduleList);
                }

            }
        }

        PageInfo< ? > pageInfo = new PageInfo<>(projectManagers);
        return PageResult.success(projectManagers, new ArrayList<>(), "", pageInfo.getTotal());
    }


    /**
     * 项目管理 重新提交
     *
     * @param projectSchedule
     * @return JsonData JsonData类型
     */
    @Override
    public JsonData updateResubmit(ProjectSchedule projectSchedule) {
        ProjectManager projectManager = ProjectManager.builder()
                .auditStatus("0")
                .operate("submit")
                .id(projectSchedule.getProjectId())
                .build();
        int num = projectManagerMapper.updateByPrimaryKeySelective(projectManager);
        if (num > 0) {
            int num1 = projectScheduleMapper.updateProjectSchedule(projectSchedule);
            if (num1 > 0) {
                return JsonData.success("", 906);
            }
        }
        return JsonData.success("", 911);
    }

    @Override
    public JsonData saveColumns(String id, String columns, String values) {
        if (columns != null && columns != "") {
            String sql = "update pms_project_manager set ";
            String saveSql = "";
            String[] column = columns.split(",");
            String[] value = values.split(",");
            for (int i = 0; i < column.length; i++) {
                if (saveSql == "") {
                    saveSql += column[i] + "= '" + value[i] + "'";
                } else {
                    saveSql += "," + column[i] + "= '" + value[i] + "'";
                }
            }

            if (saveSql != "") {
                sql += saveSql + " where id = '" + id + "'";
                projectManagerMapper.saveColumns(sql);
            }
        }
        return JsonData.success("", 906);
    }
}
